﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Red.GameData.Raw
{
    /// <summary>
    /// Class representing default value override in given class
    /// </summary>
    public class ReflectionDefaultValue
    {
        /// <summary>
        /// Name of the property this default value is for
        /// </summary>
        public string Name { get; private set; }

        /// <summary>
        /// Default value to assign to property
        /// </summary>
        public string Value { get; private set; }

        /// <summary>
        /// Parent reflection class this default value was defined in
        /// Can be used as a cheap way to get to the ReflectionData "singleton"
        /// </summary>
        public ReflectionClass Parent { get; private set; }

        /// <summary>
        /// Create default value holder
        /// </summary>
        internal ReflectionDefaultValue(ReflectionClass parent, string name, string value)
        {
            Parent = parent;
            Name = name;
            Value = value;
        }

        /// <summary>
        ///  XML shitty parsing - Load default value definition from XML node
        /// </summary>
        /// <param name="parent">Parent reflection class</param>
        /// <param name="log">Progress/error reporting interface</param>
        /// <param name="node">XML node to load from</param>
        /// <returns>True if the loading was successful or false if there were errors</returns>
        public static bool LoadFromNode(ReflectionClass parent, IGenericFileErrorReporter log, XmlNode node)
        {
            // 'name' attribute is required
            string propName = Raw.Utils.Attr(node, "name");
            if (propName == "")
            {
                log.Error(String.Format("Missing attribute 'name' for default value of class {0}", parent.Name));
                return false;
            }

            // 'type' attribute is also required
            string propValue = Raw.Utils.AttrMaybe(node, "value");
            if (propValue == null)
            {
                log.Error(String.Format("Missing attribute 'value' for property {1} of class {0}", parent.Name, propName));
                return false;
            }

            // create reflection property 
            var defaultValue = new ReflectionDefaultValue(parent, propName, propValue);
            parent.ClassDefaultValues.Add(defaultValue);

            // no loading errors
            return true;
        }

    }
}
